<template>
  <div id="book-management">
    <el-row :gutter="10">
      <el-col :span="6">
        <el-input
          placeholder="输入书籍名称搜索"
          v-model="searchKeyword"
          @input="searchBooks"
          @keyup.enter.native="searchBooks"
        />
      </el-col>
      <el-col :span="6">
        <!-- 查询按钮 -->
        <el-button type="primary" @click="searchBooks">查询</el-button>
        <!-- 新增书籍按钮，与查询按钮并排 -->
        <el-button
          type="success"
          @click="showAddBookDialog()"
          style="margin-left: 15px"
          >新增书籍</el-button
        >
      </el-col>
    </el-row>
    <!-- 图书表格 -->
    <el-table
      ref="multipleTable"
      :data="books"
      tooltip-effect="dark"
      stripe
      style="width: 100%; margin-top: 20px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="bookId" label="编号" width="80"></el-table-column>
      <el-table-column prop="title" label="书名" width="150"></el-table-column>
      <el-table-column label="封面" width="200">
        <template #default="{ row }">
          <img
            :src="row.coverImageUrl"
            alt=""
            style="width: 160px; height: 180px"
          />
        </template>
      </el-table-column>
      <el-table-column prop="author" label="作者"></el-table-column>
      <el-table-column prop="category.name" label="分类"></el-table-column>
      <el-table-column prop="price" label="价格"></el-table-column>
      <el-table-column prop="stock" label="库存"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="viewDetails(scope.row)"
            >详情</el-button
          >
          <el-button type="text" size="small" @click="editBook(scope.row)"
            >编辑</el-button
          >
          <el-popover
            placement="top"
            title="删除确认"
            width="160"
            trigger="click"
          >
            <p>确定删除该书籍吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs.popover.hide()"
                >取消</el-button
              >
              <el-button
                type="primary"
                size="mini"
                @click="deleteBook(scope.row.id)"
                >确定</el-button
              >
            </div>
            <el-button slot="reference" type="text" size="small"
              >删除</el-button
            >
          </el-popover>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      layout="prev, pager, next"
      :total="totalBooks"
      :page-size="pageSize"
      @current-change="handlePageChange"
      style="text-align: center; margin-top: 20px"
    ></el-pagination>

    <el-button v-if="selected.length > 0" type="danger" @click="batchDelete"
      >批量删除</el-button
    >

    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="50%">
      <el-form
        :model="bookData"
        ref="bookForm"
        :rules="bookRules"
        label-width="120px"
      >
        <el-form-item label="书名" prop="title">
          <el-input v-model="bookData.title"></el-input>
        </el-form-item>
        <el-form-item label="封面图片">
          <el-upload
            action="http://your-backend-api/upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :file-list="fileList"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogImageUrlVisible">
            <img
              :src="dialogImageUrl"
              alt="Preview Image"
              style="width: 100%"
            />
          </el-dialog>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="bookData.categoryId" placeholder="请选择">
            <el-option
              v-for="item in categories"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="bookData.author"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="bookData.price"
            :controls="false"
          ></el-input-number>
        </el-form-item>
        <!-- 其他字段类似添加 -->
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm('bookForm')"
          >保存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { definedSearch } from "@/store/store";
import API from "../../api/API";

export default {
  name: "BookInfo",
  data() {
    return {
      books: [],
      searchKeyword: "",
      // bookData: [], // 假设这是从API获取的书籍列表
      filteredBooks: [],
      selected: [], //选中的书籍
      dialogVisible: false,
      dialogTitle: "新增书籍",

      dialogImageUrlVisible: false,
      dialogImageUrl: "",
      fileList: [],
      categories: [
        { value: 1, label: "科技" },
        { value: 2, label: "小说" },
      ], // 示例分类数据
      bookRules: {
        // 表单验证规则
        title: [{ required: true, message: "请输入书名", trigger: "blur" }],
        categoryId: [
          { required: true, message: "请选择分类", trigger: "change" },
        ],
        author: [{ required: true, message: "请输入作者", trigger: "blur" }],
        price: [{ required: true, message: "请输入价格", trigger: "blur" }],
      },

      bookData: {
        title: "",
        author: "",
        publisher: "",
        price: 0,
        stock: 0,
        description: "",
        coverImageUrl: "",
        categoryId: 1,
      },
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示的记录数
      totalBooks: 0, // 总记录数
    };
  },
  computed: {
    filteredBooks() {
      return this.books.filter((book) =>
        book.title.toLowerCase().includes(this.searchKeyword.toLowerCase())
      );
    },
  },
  beforeUpdate(){
    this.books = definedSearch().bookData
  },
  methods: {
    refresh() {
      location.reload();
    },
    searchBooks() {
      let newItem = {
        search: "",
      };
      newItem.search = this.searchKeyword;
      API.getSearchBooks(this.searchKeyword)
        .then((response) => {
          if (response.data.status == 200) {
            console.log("成功"); 
            definedSearch().bookData = response.data.data.books
          } else {
            console.error("搜索失败");
          }
        })
        .catch(() => {});
      console.log("搜索书籍");
      // 调整fetchBooks方法以支持搜索
      // 更新fetchBooks方法以包含搜索关键词、当前页码和页面大小
      this.fetchBooks(this.currentPage, this.pageSize, this.searchKeyword);
    },
    // 分页处理方法
    handlePageChange(page) {
      this.currentPage = page;
      // 调整fetchBooks方法以支持分页
      this.fetchBooks(page, this.pageSize);
    },
    handleSelectionChange(val) {
      this.selected = val.map((item) => item.id);
    },
    showAddBookDialog() {
      console.log("新增书籍");
      this.dialogVisible = true;
      this.dialogTitle = "新增书籍";
      this.bookData = {
        title: "",
        author: "",
        publisher: "",
        price: 0,
        stock: 0,
        description: "",
        coverImageUrl: "",
        categoryId: 1,
      };
    },
    viewDetails(book) {
      // 查看详情逻辑
    },
    editBook(book) {
      this.dialogTitle = "编辑书籍";
      this.bookData = { ...book };
      this.dialogVisible = true;
    },
    deleteBook(bookId) {
      API.deleteBook(bookId)
        .then(() => {
          this.$message.success("书籍删除成功");
          this.fetchBooks();
        })
        .catch(() => {
          this.$message.error("删除失败");
        });
    },
    batchDelete() {
      if (this.selected.length === 0) return;
      this.$confirm("确定删除选中的书籍吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        // 执行批量删除的API请求
        API.deleteBook({ ids: this.selected })
          .then(() => {
            this.$message.success("批量删除成功");
            this.fetchBooks();
          })
          .catch(() => {
            this.$message.error("批量删除失败");
          });
      });
    },
    saveBook() {
      // 根据dialogTitle判断是添加还是更新
      const method = this.dialogTitle === "新增书籍" ? "post" : "put";
      axios[method]("/api/books", this.bookForm)
        .then((response) => {
          this.$message.success(response.data.message);
          this.dialogVisible = false;
          this.fetchBooks();
        })
        .catch(() => {
          this.$message.error("保存失败");
        });
    },
    //书籍列表
    fetchBooks(page = 1, pageSize = 10, keyword = "") {
      API.getBooks({ page, pageSize, keyword }) // 假设API支持接收keyword参数
        .then((response) => {
          this.books = response.data.data;
          this.totalBooks = response.data.total;

          // 如果有搜索关键词，过滤数据
          if (keyword) {
            this.filteredBooks = this.books.filter((book) =>
              book.title.toLowerCase().includes(keyword.toLowerCase())
            );
          } else {
            this.filteredBooks = this.books; // 否则直接使用获取到的数据
          }
        })
        .catch((error) => {
          console.error("Error fetching books:", error);
        });

      this.filteredBooks = this.books;
    },
    //上传图片

    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrlVisible = true;
      this.dialogImageUrl = file.url;
    },
    beforeUpload(file) {
      // 在这里可以进行文件格式校验等操作
      this.fileList = [file]; // 假设只上传一张图片
      return false; // 阻止自动上传，这里仅作展示
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 发送数据到后端
          this.saveBook();
        } else {
          console.log("表单验证失败！");
          return false;
        }
      });
    },
    // 更新saveBook方法以处理上传的图片和其他数据
    saveBook() {
      // 假设图片已上传至服务器，这里使用fileList的第一张图片URL作为封面
      const formData = new FormData();
      formData.append("title", this.bookData.title);
      formData.append("author", this.bookData.author);
      formData.append("price", this.bookData.price);
      formData.append("categoryId", this.bookData.categoryId);
      if (this.fileList.length) {
        formData.append("coverImageUrl", this.fileList[0].raw); // 原始文件对象
      }

      API.addBook(formData)
        .then((response) => {
          this.$message.success(response.data.message);
          this.dialogVisible = false;
          this.fetchBooks(); // 刷新表格数据
        })
        .catch(() => {
          this.$message.error("保存失败");
        });
    },
  },
  mounted() {
    this.fetchBooks();
  },
};
</script>
